const uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const gulp = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const connect = require('gulp-connect');
// 自动兼容 需要配置package.json
const autoPrefixer = require('gulp-autoprefixer');
const sourcemaps = require("gulp-sourcemaps")
const htmlmin = require('gulp-htmlmin');
const webserver = require('gulp-webserver')

/* 打包 scss */
function scssHandler() {
    return gulp
        .src('./src/styles/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass())
        .pipe(autoPrefixer())
        .pipe(sourcemaps.write('./'))

        .pipe(gulp.dest('./dist/styles'))
        .pipe(connect.reload())
}

/* 打包 js */
function jsHandler() {
    return gulp
        .src('./src/**/*.js')
        // .pipe(babel({
        //     presets: ['@babel/env']
        // }))
        // .pipe(uglify())
        .pipe(gulp.dest('./dist'))
        .pipe(connect.reload())
}

/* 打包 html */
function htmlHandler() {
    return gulp
        .src(['./src/**/*.html', './src/*.html'])
        .pipe(htmlmin({
            removeComments: true,
        }))
        .pipe(gulp.dest('./dist'))
        .pipe(connect.reload())
}

/* 打包 图片 */
function imgHandler() {
    return gulp
        .src('./src/img/**/*')
        .pipe(gulp.dest('./dist/img'))
        .pipe(connect.reload())
}

/* 打包 第三方 */
function libHandler() {
    return gulp
        .src('./src/lib/**/*')
        .pipe(gulp.dest('./dist/lib'))
        .pipe(connect.reload())
}

/* 打包数据 */
function dataHandler() {
    return gulp
        .src('./src/data/**')
        .pipe(gulp.dest('./dist/data'))
}

/* 监听 */
function watch(done) {
    /* 监听 scss */
    gulp.watch('./src/styles/*.scss', gulp.series(scssHandler));
    /* 监听 js */
    gulp.watch('./src/**/*.js', gulp.series(jsHandler));
    /* 监听 html */
    gulp.watch(['./src/**/*.html', './src/*.html'], gulp.series(htmlHandler));
    /* 监听 img */
    gulp.watch('./src/img/**/*', gulp.series(imgHandler));
    /* 监听 lib */
    gulp.watch('./src/lib/**/*', gulp.series(libHandler));
    /* 监听 data */
    gulp.watch('./src/data/**', gulp.series(dataHandler));
    done();
}


/* 服务器 */
function server(done) {
    connect.server({
        root: 'dist',
        livereload: true
    });
    done();
}
/* web服务器 */
function webHandler() {
    return gulp
        .src('dist')
        .pipe(webserver({
            host: 'localhost',
            port: '8080',
            livereload: true,
            open: './pages/index.html'
        }))
}


module.exports.copyAll = gulp.series(scssHandler, jsHandler, htmlHandler, imgHandler, libHandler)
/* 默认任务 */
module.exports.default = gulp.series(server, watch);
// module.exports.default = gulp.series(watch, webHandler);